package com.netstar.ui.activity;

import java.util.HashMap;

import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.telephony.gsm.SmsMessage;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.netstar.R;
import com.netstar.ui.BaseActivity;
import com.netstar.util.EvtLog;
import com.netstar.util.PackageUtil;
import com.netstar.util.StringUtil;

/**
 * 流量存储主界面
 * 
 * @author zou.sq
 */
public class NetStarActivity extends BaseActivity implements OnClickListener, Runnable {

	private String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
	private static final String TAG = "NetStarActivity";
	private static final int FLOW_TOTAL = 1000;
	private static final int GET_SIM_INFO_FAIL = 0;
	private static final int SIM_CAN_NOT_SUPPORT = 1;
	private static final int RECEIVED_MESSAGE_SUCCESS = 2;

	private static final int MENU_SETTINGS = 1;
	private static final int MENU_EXIT = 3;

	private Button mBtnFlowSave; // 流量储蓄
	private Button mBtnFlowCheck; // 流量校正
	private Button mFlowApply; // 申请流量
	private ImageView mFlowPointer; // 流量指针
	private LinearLayout mLlCheckLayout;
	private LinearLayout mLlLeftLayout;
	private TextView mTvCheck;
	private TextView mTvLeft;
	private TextView mTvFlowUsed;
	private TextView mTvFlowTotal;
	private ProgressDialog mProgressDialog;
	private boolean isReceiveBind;
	private SMSReceive mReceive;
	private Context mContext;
	private boolean mDianXin = true;

	Handler mHadler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (null != mProgressDialog && mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
			}
			EvtLog.d(TAG, "mHadler：" + msg.what);
			switch (msg.what) {
				case GET_SIM_INFO_FAIL: // 获取sim卡信息失败
					mLlCheckLayout.setVisibility(View.INVISIBLE);
					mTvCheck.setVisibility(View.VISIBLE);
					toast("获取信息失败，请重试");
					break;
				case SIM_CAN_NOT_SUPPORT: // sim卡不支持
					mLlCheckLayout.setVisibility(View.INVISIBLE);
					mTvCheck.setVisibility(View.VISIBLE);
					toast("目前只支持电信用户");
					break;
				case RECEIVED_MESSAGE_SUCCESS: // 查询流量成功
					unRegisteSMSBroadcast();
					mLlCheckLayout.setVisibility(View.INVISIBLE);
					mLlLeftLayout.setVisibility(View.VISIBLE);
					Object object = msg.obj;
					try {
						if (null != object) {
							HashMap<String, String> map = (HashMap<String, String>) msg.obj;
							String used = map.get("used");
							String total = map.get("total");
							if (!mDianXin) {
								total = FLOW_TOTAL + "";
							}
							toast("查询流量成功：" + used);
							mTvFlowTotal.setText(total + "");
							double totalFlow = Double.parseDouble(total);
							double usedFlow = Double.parseDouble(used);
							float degrees = (float) (usedFlow * 360 / totalFlow);
							mTvLeft.setText((totalFlow - usedFlow)+"");
							EvtLog.d(TAG, "旋转角度：" + degrees);
							mTvFlowUsed.setText(usedFlow + "");
							if (PackageUtil.getConfigBoolean("is_developing")) {
								mBtnFlowSave.setVisibility(View.VISIBLE);
							}
							if (Double.parseDouble(used) >= 200) {
								mBtnFlowSave.setVisibility(View.VISIBLE);
							}
							mFlowPointer.setAnimation(getPointerAnimation(degrees - 90));
						}
					} catch (Exception e) {
						EvtLog.d(TAG, e.toString());
					}
					break;
				default:
					break;
			}
		}
	};

	private RotateAnimation getPointerAnimation(float toDegrees) {
		RotateAnimation animation = new RotateAnimation(
				-90, toDegrees, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		animation.setDuration(1000);
		animation.setFillAfter(true);
		return animation;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main);
		EvtLog.d(TAG, "onCreate");
		initVariables();
		initViews();
		setListener();
	}

	private void initVariables() {
		mContext = this;
	}

	private void setListener() {
		mBtnFlowSave.setOnClickListener(this);
		mBtnFlowCheck.setOnClickListener(this);
		mFlowPointer.setOnClickListener(this);
		mFlowApply.setOnClickListener(this);
	}

	public void initViews() {
		mBtnFlowSave = (Button) findViewById(R.id.btn_flow_save);
		mBtnFlowCheck = (Button) findViewById(R.id.btn_flow_check);
		mFlowPointer = (ImageView) findViewById(R.id.iv_flow_pointer);
		mFlowApply = (Button) findViewById(R.id.btn_flow_apply);
		mLlCheckLayout = (LinearLayout) findViewById(R.id.ll_checking);
		mLlLeftLayout = (LinearLayout) findViewById(R.id.ll_left);
		mTvCheck = (TextView) findViewById(R.id.tv_check);
		mTvLeft = (TextView) findViewById(R.id.tv_left);
		mTvFlowUsed = (TextView) findViewById(R.id.tv_flow_used);
		mTvFlowTotal = (TextView) findViewById(R.id.tv_flow_total);
		mTvCheck.setVisibility(View.VISIBLE);
		mBtnFlowSave.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
			case R.id.btn_flow_save:
				Intent saveIntent = new Intent(mContext, FlowSaveActivity.class);
				startActivity(saveIntent);
				break;
			case R.id.btn_flow_check:
				registeSMSBroadcast();
				mProgressDialog = ProgressDialog.show(this, "", "自动检测中，请稍等···");
				mLlCheckLayout.setVisibility(View.VISIBLE);
				mTvCheck.setVisibility(View.INVISIBLE);
				mLlLeftLayout.setVisibility(View.INVISIBLE);
				new Thread(this).start(); // 子线程发送短信
				break;
			case R.id.btn_flow_apply:
				Intent freeintent = new Intent(mContext, ApplyFreeActivity.class);
				startActivity(freeintent);
				break;
		}
	}

	/**
	 * 注册短信广播
	 */
	private void registeSMSBroadcast() {
		EvtLog.d(TAG, "注册广播");
		isReceiveBind = true;
		mReceive = new SMSReceive();
		IntentFilter intent = new IntentFilter();
		intent.addAction(SMS_RECEIVED_ACTION);
		intent.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		registerReceiver(mReceive, intent);
	}

	private void unRegisteSMSBroadcast() {
		if (isReceiveBind && null != mReceive) {
			unregisterReceiver(mReceive);
			isReceiveBind = false;
		}
	}

	class SMSReceive extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (null == intent) {
				return;
			}
			String action = intent.getAction();
			if (SMS_RECEIVED_ACTION.equals(action)) {
				EvtLog.d(TAG, "收到短信");
				Bundle bundle = intent.getExtras();
				if (bundle != null) {
					Object[] pdus = (Object[]) bundle.get("pdus");
					int length = pdus.length;
					// 解析短信
					SmsMessage[] messages = new SmsMessage[length];
					for (int i = 0; i < length; i++) {
						byte[] pdu = (byte[]) pdus[i];
						messages[i] = SmsMessage.createFromPdu(pdu);
					}
					// 解析完内容后分析具体参数
					for (SmsMessage msg : messages) {
						String Gprs = msg.getMessageBody();
						String sender = msg.getOriginatingAddress();
						String numberString = "";
						if (mDianXin) {
							numberString = "10001";
						}
						if (numberString.equals(sender)) {
							String total = "";
							String used = "";
							String flagString = "";
							String flagShengyu = "";
							if (mDianXin) {
								flagString = "总流量为";
								flagShengyu = "使用流量";
							}
							EvtLog.d(TAG, "短信内容：" + Gprs);
							if (Gprs.indexOf(flagString) != -1) {

								total = Gprs.substring(Gprs.indexOf(flagString) + 4, Gprs.indexOf("MB"));
								used = Gprs.substring(Gprs.indexOf(flagShengyu) + 4, Gprs.lastIndexOf("MB"));
								Message msg1 = new Message();
								msg1.what = 2;
								HashMap<String, String> map = new HashMap<String, String>();
								map.put("used", used);
								map.put("total", total);
								msg1.obj = map;
								EvtLog.d(TAG, "联通流量：" + used);
								mHadler.sendMessage(msg1);
							}
							abortBroadcast();
						}
					}
				}
			}
		}

	}

	@Override
	public void run() {
		sendMessage();
	}

	/**
	 * 发送短信
	 */
	private void sendMessage() {
		EvtLog.d(TAG, "发送短信");
		String ProvidersName = null;
		TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		SmsManager smsManager = SmsManager.getDefault();
		// 手机号码，有的手机是不能获取的
		// String tel_num = telephonyManager.getLine1Number();
		String IMSIinfo = telephonyManager.getSubscriberId(); // 国际移动用户识别码
		if (StringUtil.isNullOrEmpty(IMSIinfo)) {
			mHadler.sendEmptyMessage(GET_SIM_INFO_FAIL);
			EvtLog.d(TAG, "获取SIM信息失败");
			return;
		}
		if (IMSIinfo.startsWith("46000") || IMSIinfo.startsWith("46002")) {
			EvtLog.d(TAG, "中国移动");
			// ProvidersName = "中国移动";
			// PendingIntent mPI = PendingIntent.getBroadcast(this, 0,
			// new Intent(), 0);
			// smsManager.sendTextMessage("10086", null, "CXGPRS10", mPI, null);
			mHadler.sendEmptyMessage(SIM_CAN_NOT_SUPPORT);
			return;
		} else if (IMSIinfo.startsWith("46001")) {
			EvtLog.d(TAG, "中国联通");
			if (!mDianXin) {
				ProvidersName = "中国联通";
				PendingIntent mPI = PendingIntent.getBroadcast(this, 0, new Intent(), 0);
				smsManager.sendTextMessage("10010", null, "CXGPRSLL", mPI, null);
			} else {
				mHadler.sendEmptyMessage(SIM_CAN_NOT_SUPPORT);
			}
			return;
		} else if (IMSIinfo.startsWith("46003")) {
			EvtLog.d(TAG, "中国电信");
			ProvidersName = "中国电信";
			PendingIntent mPI = PendingIntent.getBroadcast(this, 0, new Intent(), 0);
			smsManager.sendTextMessage("10001", null, "108", mPI, null);
		}
		EvtLog.d(TAG, "发送短信成功");
		EvtLog.d(TAG, "ProvidersName = " + ProvidersName);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_SETTINGS, 0, "设置").setIcon(android.R.drawable.ic_menu_preferences);
		// menu.add(0, MENU_LOGIN, 1, "注册").setIcon(
		// android.R.drawable.ic_menu_info_details);
		menu.add(0, MENU_EXIT, 3, "退出").setIcon(android.R.drawable.ic_menu_revert);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
			case MENU_SETTINGS:
				startActivity(new Intent(this, SettingsActivity.class));
				break;
			// case MENU_LOGIN:
			// startActivity(new Intent(this, LoginActivity.class));
			// break;
			case MENU_EXIT:
				finish();
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		unRegisteSMSBroadcast();
		super.onDestroy();
	}
}